package com.fs.ssm004.service.impl;

import com.fs.ssm004.Dao.TeacherDao;
import com.fs.ssm004.pojo.Teacher;
import com.fs.ssm004.service.TeacherService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TeacherServiceImpl implements TeacherService {
    private TeacherDao teacherDao;

    @Autowired
    public TeacherServiceImpl(TeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    @Override
    public Map<String, Object> login(String teacherName, String password) {
        Map<String, Object> result = new HashMap<>();
        //获取shiro系统认为的当前用户
        Subject currentTeacher = SecurityUtils.getSubject();
        //判断是否认证，认证过就不认证
        if (!currentTeacher.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(teacherName, password);
            //让系统记住你，会保存用户信息到浏览器，下次如果需要授权，使用该身份
            token.setRememberMe(true);
            //shiro执行登录
            try {
                currentTeacher.login(token);
            } catch (UnknownAccountException e) {
                result.put("code", -3);
                result.put("message", "没有查到该人");
                return result;
            } catch (IncorrectCredentialsException e) {
                result.put("code", -2);
                result.put("message", "密码输入错误");
                return result;
            } catch (AuthenticationException e) {
                result.put("code", -4);
                result.put("message", "登录失败");
                return result;
            }
        }
        Teacher teacher = (Teacher) currentTeacher.getSession().getAttribute("teacher");
        result.put("code", 0);
        result.put("teacher", teacher);
//        result.put("roleNum",teacher.getRoleNum());
        result.put("roleNum",teacher.getRoleNum());
        result.put("message", teacher.getName()+"恭喜登录成功");
        return result;
    }

    @Override
    public Teacher getOneByTeachername(String teacherName) {
        return teacherDao.queryByTeachername(teacherName);
    }

    @Override
    public Teacher logout() {
        Subject currentTeacher = SecurityUtils.getSubject();
        Teacher teacher = (Teacher)currentTeacher.getSession().getAttribute("teacher");
        //退出shiro系统的当前用户
        currentTeacher.logout();
        return teacher;
    }
}
